/*****************************************************************************
 * javascript for paging
 *
 * version : v0.1
 * version : v0.2 增加page_ctrl_class，可以修改page控件关联的class
 *                主要用在一个html中使用多个page控件的场合
 * version : v0.3 增加search_condition，增加检索条件的字典
 *
 * base on : jquery 1.10.2
 *           bootstrap v3
 *           chujue_ajax.js
 *****************************************************************************/


var Chujue_Paginator = function(){

    this.target_id = "";        // 显示数据的table的id
    this.first_page_num = 1;    // 当前显示的页面中的最小页面号 
    this.current_page = 1;      // 当前页面编号，默认是第一个页面
    this.total_page = 1;        // 总页面数
    this.items_per_page = 3;    // 每页显示的项目个数(默认每页显示3个项目)
    this.pages_for_display = 5; // 显示的分页按钮个数(默认 |<< < 1 2 3 4 5 > >>|)
    this.data_template = [];    // table中包含的项目名称数组
    this.tr_html = "";          // table中一行 tr 的html代码

    this.url = "";              // 获取 page 数据的 ajax url
    this.page_ctrl_class = "";  // page 控件的 class
    this.search_condition = {}; // page中数据的检索条件
    
    var _this = this;           // 保存当前对象
    
    this.init = function(target_id, data_template, tr_html, url) {
        _this.target_id = target_id;
        _this.data_template = data_template;
        _this.tr_html = tr_html;
        _this.url = url;

        if (_this.page_ctrl_class == "")
            _this.page_ctrl_class = ".chujue-paginator";

        _this.change_page();      
    };

    this.set_page_ctrl = function(class_name) {
        _this.page_ctrl_class = class_name;
    }

    this.set_s_condition = function(conditions) {
        _this.search_condition = conditions;
    }

    this.set_page_state = function() {
        var all_pages = _this.page_ctrl_class + " > li";
        $(all_pages).removeClass("disabled");
        $(all_pages).removeClass("active");
        
        // 第一页
        if (_this.current_page == 1) {
            $(all_pages + ":eq(0)").addClass("disabled"); // <<
            $(all_pages + ":eq(1)").addClass("disabled"); // <
            $(all_pages + ":eq(2)").addClass("active");   // page 1
        }
        // 最后一页
        if (_this.current_page == _this.total_page) {
            $(all_pages + ":eq(-1)").addClass("disabled"); // >>
            $(all_pages + ":eq(-2)").addClass("disabled"); // >            
            $(all_pages + ":eq(-3)").addClass("active");   // page last
        }
        // 其他页
        if (_this.current_page > 1 && _this.current_page < _this.total_page) {
            var num = (_this.current_page-_this.first_page_num) + 2; // +2 for << <
            $(all_pages + ":eq("+ num.toString() +")").addClass("active");
        }
    };

    this.set_page_num = function() {

        var cj_page = $(_this.page_ctrl_class);
        // 调整 first page 的号
        if (_this.current_page < _this.first_page_num ||
            (_this.current_page - _this.first_page_num) >= _this.pages_for_display)
            // 将当前页 放到已显示页面号的中间
            _this.first_page_num = _this.current_page - (_this.pages_for_display-1) / 2;

        // current_page <= (pages_for_display-1)/2 的情况，即 current_page 接近 first_page
        if (_this.first_page_num < 1)
            _this.first_page_num = 1;
        // current_page 接近 last_page 的情况
        if (_this.total_page > _this.pages_for_display &&
            _this.total_page - _this.first_page_num < _this.pages_for_display)
            _this.first_page_num = _this.total_page - _this.pages_for_display + 1;
        
        // 创建分页按钮
        var page_count = _this.total_page - _this.first_page_num + 1;
        if (page_count > _this.pages_for_display)
            page_count = _this.pages_for_display;
        for (var i=0; i<page_count + 4; i++) // +4 for << < > >>
            cj_page.append('<li><a href="#"></a></li>');

        var all_pages_a = _this.page_ctrl_class + " > li > a";
        // 设置 << < > >>
        $(all_pages_a + ":eq(0)").text("<<");
        $(all_pages_a + ":eq(1)").text("<");
        $(all_pages_a + ":eq(-1)").text(">>");
        $(all_pages_a + ":eq(-2)").text(">");

        // 设置页面号
        for (var i=0; i< page_count; i++)
            $(all_pages_a + ":eq("+(i+2).toString()+")").text(_this.first_page_num+i);
    };

    this.set_page_event = function() {
        var all_pages_a = _this.page_ctrl_class + " > li > a";
        // 设置 << < > >>
        if (_this.current_page != 1) {
            $(all_pages_a + ":eq(0)").click(_this.first_page);
            $(all_pages_a + ":eq(1)").click(_this.prev_page);
        }
        if (_this.current_page != _this.total_page) {
            $(all_pages_a + ":eq(-1)").click(_this.last_page);
            $(all_pages_a + ":eq(-2)").click(_this.next_page);
        }

        // 设置页面号
        for (var i=0; i< $(all_pages_a).length - 4; i++) {
            if ((_this.first_page_num + i) == _this.current_page)
                continue;
            
            $(all_pages_a + ":eq("+(i+2).toString()+")")
                .click(_this.first_page_num + i, _this.goto_page);
        }
    };

    /* update datatable after ajax
     * data format:
     * {
     *     "result"    : "OK" or "NG",
     *     "message"   : "xxxx",
     *     "total_page": xxx,
     *     "datatable" : [
     *         {
     *             data_template[0] : xxxx,
     *             ... ...
     *             data_template[n] : xxxx,
     *         },
     *         ... ...
     *     ]
     * }
     */
    this.update_table = function(data) {
        // alert(data);
        
        // 清空 数据表中所有数据
        var tbody = $("#" + _this.target_id + " > tbody");
        tbody.empty(); // clear all tr
        
        // 清空已有分页
        var cj_page = $(_this.page_ctrl_class);
        cj_page.empty();

        _this.total_page = data["total_page"];
        if (_this.total_page == 0)
            return;

        if (_this.total_page > 1) {
            // set page num and state
            _this.set_page_num();
            _this.set_page_state();
            _this.set_page_event();
        }

        for (var i=0; i<data["datatable"].length; i++) {
            var temp_tr = _this.tr_html;
            var temp_tr_data = data["datatable"][i];
            for (var j=0; j<_this.data_template.length; j++) {
                temp_tr = temp_tr.replace(_this.data_template[j],
                                          temp_tr_data[_this.data_template[j]]);
            }
            tbody.append(temp_tr);
        }      
    };

    this.change_page = function(){

        // get data by ajax
        var page_req = new Chujue_Request();
        page_req.url = _this.url;
        page_req.pre_check = false;
        page_req.is_setmessage = false;
        page_req.send_data = {
            "current_page": _this.current_page,
            "items_per_page": _this.items_per_page,
            "conditions": _this.search_condition,
        };
        page_req.ok_func = _this.update_table;
        page_req.ajax_req();
    };

    this.next_page = function() {
        _this.current_page += 1;
        _this.change_page();
    };

    this.prev_page = function() {
        _this.current_page -= 1;
        _this.change_page();
    };

    this.first_page = function() {
        _this.current_page = 1;
        _this.change_page();
    };

    this.last_page = function() {
        _this.current_page = _this.total_page;
        _this.change_page();
    };

    this.goto_page = function(event) {
        // alert(event.data);
        _this.current_page = event.data;
        _this.change_page();
    };
};


